package com.k.kpp.config.ftp;

import com.k.kc.util.FileUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.pool2.ObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;

/**
 * @author kivil
 */
public class FtpClientTemplate {
    private final static Logger LOGGER = LoggerFactory.getLogger(FtpClientTemplate.class);
    private ObjectPool<FTPClient> pool;

    public FtpClientTemplate(FtpClientFactory factory,GenericObjectPoolConfig<FTPClient> poolConfig) {
        System.out.println("ftp.pool:"+poolConfig.toString());
        this.pool = new GenericObjectPool<>(factory,poolConfig);
    }


    /**
     *
     * @param dir dir
     * @param name name
     * @param file file
     */
    public void uploadFile(String dir,String name,File file){
        System.out.println("method: uploadFile");
        FTPClient ftpClient = null;
        try {
            ftpClient = pool.borrowObject();
            String uploadDir = FileUtils.formatDir(dir);
            System.out.println("uploadDir:" + uploadDir);
        } catch (Exception e) {
            LOGGER.error("uploadFile error:{}",e);
            e.printStackTrace();
        }finally {
            try {
                if(ftpClient != null){
                    pool.returnObject(ftpClient);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
